<?php

namespace App\Http\Controllers;

use App\Events\ApiEvent;
use App\Helper;
use App\Models\Account;
use App\Models\AuthorizeXiaohuai;
use App\Models\Character;
use App\Models\Server;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class ApiController extends Controller
{

    public function getChars(Request $request) {
        $server= Server::find($request->get('id'));
        Helper::setDataBaseConf('mysql_auth',$server,'acore_auth');
        $username=$request->get('username');
        $password=$request->get('password');
        if (!$username || !$password)
        {
            return JsonResponse::create(['err'=>1,'msg'=>'请输入完整的账户密码'],404);
        }

        $getAccount=Account::where('username',strtoupper($username))->get();
        if (sizeof($getAccount) != 1)
        {
            return JsonResponse::create(['err'=>1,'msg'=>'账号或密码错误'],404);
        }
        $acc=$getAccount[0];
        $pwd=sha1(strtoupper($username).':'.strtoupper($password));
        if ($acc->sha_pass_hash != strtoupper($pwd))
        {
            return JsonResponse::create(['err'=>1,'msg'=>'账号或密码错误'],404);
        }

        Helper::setDataBaseConf('mysql_char',$server,'acore_characters');
        $chars=Character::where('account',$acc->id)->get();

        return JsonResponse::create(['err'=>0,'data'=>['acc'=>$acc,'chars'=>$chars]]);
    }

    public function server_patch(Request $request,$id){
        $server= Server::find($id);
        if ($server){
            return [
                'id'=>$server->id,
                'domain'=> route('server',['domain'=>$server->domain]),// $server->domain.config('conf.domain'),
                'announcement'=>$server->ext['announcement'],
                'patch_info'=>explode("\n",$server->ext['patch_info']),
            ];
        }else{
            return 'error';
        }
//        return [
//            'a'=>$id,
//            'b'=>'sda',
//        ];
    }

    public function gmCommand(Request $request){
        $keys=['t','sid','api_key','command'];
        $data=$request->all($keys);
        $err="";
        $res="";
        $server=$this->check($data,$err,$keys);
        if (!$server){
            return JsonResponse::create(['err'=>$err,'res'=>$res]);
        }

        $command=$request->get('command');
        $server->RunCommand($command,$res,$err);
        event(new ApiEvent($server->id,$request->path(), $data,$res,$err));
//        event(new PlayerMoneyChangeEvent($server->user_id, $pay->server_id, $parent->player_id, 4, 1, $money*0.1, 0, $parent->money, '推荐玩家充值奖励',null,$pay->order_num));

        return JsonResponse::create(['err'=>$err,'res'=>$res]);
    }

    public function gmCommand_sendItems(Request $request){
        $keys=['t','sid','api_key','playerName','item_id'];
        $data=$request->all($keys);
        $err="";
        $res="";
        $server=$this->check($data,$err,$keys);
        if (!$server){
            return JsonResponse::create(['err'=>$err,'res'=>$res]);
        }

        $playerName=$data['playerName'];
        $subject=key_exists('subject',$data)?$data['subject']:'商城购物';
        $text=key_exists('text',$data)?$data['text']:'感谢支持!';
        $item_id=$data['item_id'];
        $count=key_exists('count',$data)?$data['count']:1;

        $command= '.send items '.$playerName.' "'.$subject.'" "'.$text.'" '.$item_id.':'.$count;
        $server->RunCommand($command,$res,$err);
        event(new ApiEvent($server->id,$request->path(), $data,$res,$err));
        return JsonResponse::create(['err'=>$err,'res'=>$res]);
    }

    public function gmCommand_sendMoney(Request $request){
        $keys=['t','sid','api_key','playerName','money'];
        $data=$request->all($keys);
        $err="";
        $res="";
        $server=$this->check($data,$err,$keys);
        if (!$server){
            return JsonResponse::create(['err'=>$err,'res'=>$res]);
        }

        $playerName=$data['playerName'];
        $subject=key_exists('subject',$data)?$data['subject']:'商城购物';
        $text=key_exists('text',$data)?$data['text']:'感谢支持!';
        $money=$data['money'];

        $command= '.send money '.$playerName.' "'.$subject.'" "'.$text.'" '.$money;
        $server->RunCommand($command,$res,$err);
        event(new ApiEvent($server->id,$request->path(), $data,$res,$err));
        return JsonResponse::create(['err'=>$err,'res'=>$res]);
    }
    //$command="character level {$character->name} $toLevel";
    //        $server->RunCommand($command,$res,$err);

    public function gmCommand_toLevel(Request $request){
        $keys=['t','sid','api_key','playerName','toLevel'];
        $data=$request->all($keys);
        $err="";
        $res="";
        $server=$this->check($data,$err,$keys);
        if (!$server){
            return JsonResponse::create(['err'=>$err,'res'=>$res]);
        }

        $playerName=$data['playerName'];
        $toLevel=$data['toLevel'];

        $command="character level $playerName $toLevel";
        $server->RunCommand($command,$res,$err);
        event(new ApiEvent($server->id,$request->path(), $data,$res,$err));
        return JsonResponse::create(['err'=>$err,'res'=>$res]);
    }



    function check($data,&$err,$keys){
//        if (!key_exists('t',$data)){
//            $err = '缺少时间戳';
//            return null;
//        }
//        if (!key_exists('sid',$data)){
//            $err = '缺少服务器id';
//            return null;
//        }
//        if (!key_exists('api_key',$data)){
//            $err = '缺少api_key';
//            return null;
//        }
        foreach ($keys as $key){
            if (!key_exists($key,$data)){
                $err = '缺少'.$key;
                return null;
            }
        }


//        $t=$data['t'];
//        $t_sys=time();

//        if ($t>$t_sys || $t_sys-$t>1000){
//            $err = '无效的时间戳';
//            return null;
//        }

        $sid=$data['sid'];
        $api_key=$data['api_key'];
        $server=Server::find($sid);
        if (!$server){
            $err = '无效的服务器id';
            return null;
        }
        if (!$server->enable){
            $err = '服务器到期';
            return null;
        }
        if ($server->api_key==null || $server->api_key==''){
            $err = 'api功能未开启';
            return null;
        }
        if ($server->api_key!=$api_key){
            $err = 'api_key错误';
            return null;
        }
        return $server;
    }

    private $key = "9kZSI6IkRQIiwicGFpZFVwVG8iOiIyMDIzLTA0LT";
    function authorize_xiaohuai(Request $request){
        $data=$request->all();
        if (md5($data['guid'].$this->key.$data['t'])!==$data['sign']){
            return 'errSign';
        }
        $item=AuthorizeXiaohuai::where('guid',$data['guid'])->first();
        if ($item){
            $t=time();
            return md5($this->key.$t)."|".$t;
        }else{
            return 'noGuid';
        }
    }
}
